﻿using System;
using System.IO;
using System.Net;


namespace DownloadTool.Achi
{
    class Download
    {
        // 控制线程,false时退出
        private static bool ctl = true;

        private static String task;
        private String[] urls;
        private static Stream bs;
        private static FileStream fs;
        //存放目录,根据当前日期进行创建
        public static String dir = Util.CurrentDir.dir + @"\Els\";
        public static String log = "";
        public static String Task
        {
            get { return task; }
        }

        public Download(String[] urls)
        {
            log = "";
            ctl = true;
            this.urls = urls;
        }
        public void download()
        {
            //如果不存在该目录,则创建
            Util.Folder.create(dir);

            foreach (String url in urls)
            {
                task = url;
                int n = url.LastIndexOf("/");
                //目标主机目录
                String URLAddress = url.Substring(0, n);
                //目标文件名
                String fileName = url.Substring(n + 1);
                
                //文件存放路径
                String path = dir + "\\" + fileName;

                // 如果文件存在,则跳过.并记录日志
                if (!File.Exists(path))
                {

                    //创建链接,并捕获可能出现的异常
                    try
                    {
                        using (WebClient client = new WebClient())
                        {
                            ClientInit(client, fileName);
                            bs = client.OpenRead(url);
                            fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                            byte[] mbyte = new byte[1024 * 4];
                            int len = mbyte.Length;
                            int m = 0;
                            while (ctl && (m = bs.Read(mbyte, 0, len)) > 0)
                            {
                                fs.Write(mbyte, 0, m);
                            }
                            if (!ctl)
                            {
                                closeStream();
                                File.Delete(path);
                                log += "...Alert: " + fileName + "已取消下载......\r\n";
                                break;
                            }
                            else
                            {
                                log += "文件: \"" + fileName + "\"下载完成\r\n";
                            }
                        }
                    }
                    catch (Exception)
                    {
                        log += "......Error: " + fileName + "文件下载失败........\r\n";
                    }
                    finally
                    {
                        closeStream();
                    }
                }
                else
                {
                    log += "...Alert: 文件" + fileName + "已存在,自动跳过......\r\n";
                }
            }
            try
            {
                Finish();
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
            }
        }

                /// <summary>
        /// 下载完成, 弹出提示窗口
        /// </summary>
        public void Finish()
        {
            Achi.DownloadAcomplete da = new Achi.DownloadAcomplete(Achi.Download.log);
            da.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            da.Focusable = false;
            da.ShowDialog();
        }
    

        /// <summary>
        /// 关闭文件流
        /// </summary>
        public static void closeStream()
        {
            if (fs != null)
            {
                fs.Close();
            }
            if (bs != null)
            {
                bs.Close();
            }

        }

        /// <summary>
        /// 终止下载
        /// </summary>
        public static void stop()
        {
            ctl = false;
        }

        /// <summary>
        /// 添加标头
        /// </summary>
        /// <param name="client"></param>
        /// <param name="fileName"></param>
        public void ClientInit(WebClient client,String fileName)
        {
            client.Headers.Add(HttpRequestHeader.Upgrade, "GET /els/" + fileName + " HTTP/1.1");
            client.Headers.Add(HttpRequestHeader.Accept, "*/*");
            client.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN");
            client.Headers.Add(HttpRequestHeader.Referer, "http://els.ztgame.com/index_swf/playmp3.swf");
            client.Headers.Add("x-flash-version", "13,0,0,214");
            client.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
            client.Headers.Add("DNT", "1");
            client.Headers.Add(HttpRequestHeader.Connection, "True");
        }
 
    }
}
